import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:landlore/customWidget/homePageDisplayCardAmountWidget.dart';
import 'package:landlore/model/orderVO.dart';
import 'package:landlore/screens/checkingEleWaterScreen.dart';
import 'package:landlore/screens/outputBillScreen.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:landlore/screens/recordDetailFullScreen.dart';

import '../consts.dart';
import '../dbUtil/databaseHelper.dart';
import '../screens/recordDetailScreen.dart';
import 'homePageCircleWidget.dart';

class HomePageRoomDisplayCard extends StatelessWidget {
  final OrderVO orderVO;
  final Function popCallback;

  const HomePageRoomDisplayCard(
      {super.key, required this.orderVO, required this.popCallback});

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      //未抄表状态,点击卡片可以查看全部记录
      //已抄表和已出单状态,点击卡片显示当前月详情
      onTap: () async {
        if (orderVO.state == OrderState.FINISHED || orderVO.state == OrderState.BILL_OUT) {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => RecordDetailScreen(orderOV: orderVO)));
        } else if (orderVO.state == OrderState.WAITING) {
          await Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) =>
                      RecordDetailFullScreen(orderOV: orderVO)));
        }
      },
      child: Stack(children: [
        //==================主体Card部分==================
        SizedBox(
          height: 220.h,
          child: Card(
            elevation: 10,
            margin: EdgeInsets.only(
                left: 12.w, right: 12.w, top: 45.h, bottom: 25.h),
            // margin: titleOverFlow
            //     ? EdgeInsets.only(
            //         left: 12.w, right: 12.w, top: 45.h, bottom: 25.h)
            //     : EdgeInsets.only(
            //         left: 12.w, right: 12.w, top: 30.h, bottom: 25.h),
            child: AnimatedContainer(
              duration: const Duration(seconds: 1),
              curve: Curves.easeInCirc,
              color: orderVO.state == OrderState.WAITING
                  ? const Color(0xffe8d4c4)
                  : orderVO.state == OrderState.FINISHED
                      ? const Color(0xff5fa8d3)
                      : const Color(0xff343a40),
              child: Column(
                children: [
                  Container(
                    margin: EdgeInsets.only(top: 6.h, bottom: 5.h),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        SizedBox(
                          height: 68.h,
                        ),
                        Offstage(
                          offstage: orderVO.state == OrderState.BILL_OUT,
                          child: Container(
                            padding: EdgeInsets.only(right: 10.w, top: 10.h),
                            child: ElevatedButton(
                                style: const ButtonStyle(
                                    backgroundColor: MaterialStatePropertyAll(
                                        Color(0xFF2a9d8f))),
                                onPressed: () async {
                                  await Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              CheckingEleWaterScreen(
                                                orderId: orderVO.id,
                                                roomId: orderVO.roomId!,
                                                roomNum: orderVO.roomNum!,
                                                electricityAmount:
                                                    orderVO.electricityAmount ??
                                                        0,
                                                waterAmount:
                                                    orderVO.waterAmount ?? 0,
                                                eleImage:
                                                    orderVO.eleImage ?? '',
                                                waterImage:
                                                    orderVO.waterImage ?? '',
                                                currentYear:
                                                    orderVO.createDate!.year,
                                                currentMonth:
                                                    orderVO.createDate!.month,
                                                checkState:
                                                    orderVO.checkState!
                                              )));
                                  popCallback();
                                },
                                child: Text(
                                  "抄表",
                                  style: TextStyle(
                                    fontSize: 30.sp,
                                  ),
                                )),
                          ),
                        ),
                        // const SizedBox(
                        //   width: 20,
                        // )
                      ],
                    ),
                  ),
                  SizedBox(
                    height: 70.h,
                    child: Row(
                      children: [
                        Expanded(
                          flex: 2,
                          child: Container(
                            width: 290.w,
                            padding: EdgeInsets.only(left: 10.w),
                            child: Column(
                              children: [
                                DisplayCardAmountWidget(
                                    orderVO: orderVO, isEle: true),
                                SizedBox(
                                  height: 12.h,
                                ),
                                DisplayCardAmountWidget(
                                    orderVO: orderVO, isEle: false),
                              ],
                            ),
                          ),
                        ),
                        // SizedBox(
                        //   width: 20,
                        // ),
                        Expanded(
                          flex: 1,
                          child: orderVO.state == OrderState.WAITING
                              ? const SizedBox()
                              : Container(
                                  padding: EdgeInsets.only(left: 15.w),
                                  child: GestureDetector(
                                      child: Chip(
                                        label: const Text('出单'),
                                        labelStyle: TextStyle(
                                            color: Colors.black,
                                            fontSize: 20.sp),
                                        backgroundColor:
                                            const Color(0xffe1e5f2),
                                        avatar: Icon(
                                          Icons.receipt_long,
                                          color: Colors.black38,
                                          size: 30.sp,
                                        ),
                                      ),
                                      onTap: () async {
                                        if(orderVO.checkState==OrderCheckState.CHECKING_LACK_ELE || orderVO.checkState==OrderCheckState.CHECKING_LACK_WATER){
                                          final snackBar = SnackBar(
                                            content: Text(
                                              '请先完成抄表!再进行出单操作',
                                              style: TextStyle(
                                                  fontSize: 20.sp, color: Colors.redAccent),
                                            ),
                                          );
                                          ScaffoldMessenger.of(context).showSnackBar(snackBar);
                                          return;
                                        }else{
                                          await Navigator.push(
                                              context,
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      OutputBillScreen(
                                                          orderId: orderVO.id!)));
                                          //回调函数,刷新数据
                                          popCallback();
                                        }

                                      }),
                                ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        //==================房号widget==================
        Positioned(
            // top: titleOverFlow ? 10.h : -10.h,
            top: 5.h,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                ConstrainedBox(
                  constraints: const BoxConstraints(maxWidth: 380),
                  child: Container(
                      margin: EdgeInsets.only(left: 20.w),
                      padding: EdgeInsets.only(
                        left: 10.w,
                        right: 10.w,
                      ),
                      height: 55.h,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                            begin: Alignment.topLeft,end: Alignment.bottomRight,
                        colors:[Color(0xffa8dadc),Color(0xfffefae0)] ),
                          // color: const Color(0xfffefae0),
                          boxShadow: [
                            BoxShadow(
                                color: Colors.black26,
                                // offset: const Offset(-2, -4),
                                blurRadius: 20.r,
                                spreadRadius: 10.r)
                          ],
                          // image: DecorationImage(
                          //     image: AssetImage('assets/images/crossword.png'),
                          //   fit: BoxFit.fill,
                          // ),

                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(15.r),
                            topRight: Radius.circular(15.r),
                          )),
                      child: Text(
                        orderVO.roomNum!,
                        overflow: TextOverflow.ellipsis,
                        style: Consts.titleText.copyWith(fontSize: 45.sp),
                      )),
                ),
                Padding(
                  padding: EdgeInsets.only(left: 25.w, top: 5.h),
                  child: Text(
                    orderVO.contact == null ? '' : orderVO.contact!,
                    style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.w600,
                        color: orderVO.state == OrderState.BILL_OUT
                            ? Colors.white60
                            : Colors.black54),
                  ),
                ),
              ],
            )),
        ////==================状态widget==================
        Positioned(
          left: orderVO.checkState == OrderCheckState.DEFAULT ||
                  orderVO.checkState == OrderCheckState.BILL_OUT_PAID_OFF
              ? 140.w
              : 130.w,
          top: 65.h,
          child: Stack(children: [
            Container(
                margin: EdgeInsets.only(right: 23.w),
                child:
                    //两种不同风格的Tag显示,
                    // 1:chip风格.
                    // 2:圆形进度风格.
                    Consts.HOME_PAGE_TAG_STYLE
                        ? tagStyle1(
                            orderVO: orderVO,
                            popCallback: () {
                              popCallback();
                            },
                          )
                        : tagStyle2(orderVO: orderVO)),
            Positioned(
                right: 8.w,
                top: -3.h,
                child:
                    orderVO.checkState != OrderCheckState.CHECKING_LACK_ELE &&
                            orderVO.checkState !=
                                OrderCheckState.CHECKING_LACK_WATER
                        ? const SizedBox()
                        : Icon(
                            Icons.error_outlined,
                            color: Colors.red,
                            size: 30.sp,
                          ))
          ]),
        ),
        //==================收款标记图片部分==================
        Positioned(
            right: 10.w,
            top: 15.h,
            child: AnimatedSwitcher(
              duration: const Duration(milliseconds: 200),
              switchInCurve: Curves.linear,
              //out没有效果?
              switchOutCurve: Curves.easeOut,
              child: orderVO.checkState == OrderCheckState.DEFAULT
                  ? const SizedBox()
                  : orderVO.checkState == OrderCheckState.BILL_OUT_PAID_OFF
                      ? Transform.rotate(
                          angle: 3.14 / (11),
                          child: Image.asset(
                            'assets/images/state_tag_3_5.png',
                            scale: 11,
                          ))
                      : const SizedBox(),

              // Image.asset(
              //             orderVO.checkState == OrderCheckState.CHECKING_LACK_ELE
              //                 ? 'assets/images/state_tag_3_1.png'
              //                 : 'assets/images/state_tag_3_1.png',
              //             scale: 10,
              //           ),
            )),
      ]),
    );
  }
}

class tagStyle1 extends StatelessWidget {
  const tagStyle1({
    super.key,
    required this.orderVO,
    required this.popCallback,
  });

  final OrderVO orderVO;
  final Function popCallback;

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
        duration: const Duration(seconds: 1),
        transitionBuilder: (child, animation) {
          final scaleAnimation = CurvedAnimation(
            parent: animation,
            curve: Curves.easeInOut,
          );

          return ScaleTransition(
            scale: scaleAnimation,
            child: child,
          );
        },
        child: orderVO.state == OrderState.WAITING
            ? Chip(
                key: ValueKey<String>('${orderVO.roomId}0'),
                label: Text(
                  "未抄表",
                  style:
                      TextStyle(fontSize: 25.sp, fontWeight: FontWeight.w900),
                ),
                avatar: Icon(
                  Icons.error_outline,
                  size: 35.sp,
                ),
                backgroundColor: Colors.orange,
                shape: RoundedRectangleBorder(
                  side: BorderSide(color: Colors.black87, width: 3.w), // 定义边框样式
                  borderRadius: BorderRadius.circular(30.r), // 定义圆角半径
                ),
              )
            : orderVO.state == OrderState.FINISHED
                ? Chip(
                    key: ValueKey<String>('${orderVO.roomId}1'),
                    label: Text(
                      orderVO.checkState == OrderCheckState.CHECKING_LACK_ELE
                          ? "未抄电表"
                          : orderVO.checkState ==
                                  OrderCheckState.CHECKING_LACK_WATER
                              ? '未抄水表'
                              : '已抄表',
                      style: TextStyle(
                          fontSize:
                              orderVO.checkState == OrderCheckState.DEFAULT
                                  ? 23.sp
                                  : 20.sp,
                          fontWeight: FontWeight.w900),
                    ),
                    avatar: orderVO.checkState == OrderCheckState.DEFAULT
                        ? Icon(
                            Icons.check_circle_outline,
                            size: 35.sp,
                            color: Colors.black,
                          )
                        : orderVO.checkState ==
                                OrderCheckState.CHECKING_LACK_ELE
                            ? Text(
                                '⚡️',
                                style: TextStyle(fontSize: 25.sp),
                              )
                            : Text(
                                '💧',
                                style: TextStyle(fontSize: 25.sp),
                              ),
                    shape: RoundedRectangleBorder(
                      side: BorderSide(color: Colors.black, width: 3.w),
                      borderRadius: BorderRadius.circular(30.r), // 定义圆角半径
                    ),
                    backgroundColor:
                        orderVO.checkState == OrderCheckState.DEFAULT
                            ? Colors.green
                            : orderVO.checkState ==
                                    OrderCheckState.CHECKING_LACK_ELE
                                ? Colors.yellowAccent
                                : Colors.blueAccent,
                  )
                :
                // 当为已出单的状态时,可以点击,改变标签,记录支付状态
                Row(
                    children: [
                      SizedBox(
                        width: 70.w,
                      ),
                      GestureDetector(
                        onTap: () async {
                          await DatabaseHelper.instance.changeCheckState(
                              orderVO.id!, orderVO.checkState!);
                          popCallback();
                        },
                        child: Chip(
                          key: ValueKey<String>('${orderVO.roomId}2'),
                          label: Text(
                            "已出单",
                            style: TextStyle(
                                fontSize: 26.sp, fontWeight: FontWeight.w900),
                          ),
                          avatar:
                              RoundCheckbox(isChecked: orderVO.checkState == 1),
                          backgroundColor: const Color(0xfff07167),
                          shape: RoundedRectangleBorder(
                            side: BorderSide(color: Colors.black87, width: 2.w),
                            borderRadius: BorderRadius.circular(30.r), // 定义圆角半径
                          ),
                        ),
                      ),
                    ],
                  ));
  }
}

class tagStyle2 extends StatelessWidget {
  const tagStyle2({
    super.key,
    required this.orderVO,
  });

  final OrderVO orderVO;

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      duration: const Duration(milliseconds: 500),
      child: orderVO.state == OrderState.WAITING
          ? CircleWidget(
              key: ValueKey<String>('${orderVO.roomId}0'),
              numberOfSegments: 3,
              activeSegments: 1,
              orderState: 0,
            )
          : orderVO.state == OrderState.FINISHED
              ? CircleWidget(
                  key: ValueKey<String>('${orderVO.roomId}1'),
                  numberOfSegments: 3,
                  activeSegments: 2,
                  orderState: 1,
                )
              : CircleWidget(
                  key: ValueKey<String>('${orderVO.roomId}2'),
                  numberOfSegments: 3,
                  activeSegments: 3,
                  orderState: 2,
                ),
    );
  }
}

class RoundCheckbox extends StatelessWidget {
  final bool isChecked;

  const RoundCheckbox({super.key, required this.isChecked});

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 30.0.w, // 调整适合您的尺寸
      height: 30.0.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(15.0.r), // 圆角半径
        border: Border.all(
          color: Colors.grey,
          width: 2.0.w,
        ),
        color: isChecked ? Colors.blue : Colors.transparent, // 根据状态设置背景颜色
      ),
      child: isChecked
          ? const Icon(
              Icons.check,
              color: Colors.white,
            )
          : null,
    );
  }
}
